package com.wbao.dianniu.ui;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.sdk.android.media.upload.UploadListener;
import com.alibaba.sdk.android.media.upload.UploadTask;
import com.alibaba.sdk.android.media.utils.FailReason;
import com.alibaba.sdk.android.media.utils.StringUtils;
import com.arlen.photo.photopickup.presenter.HeadPresenter;
import com.wbao.dianniu.R;
import com.wbao.dianniu.customView.CustomDialog;
import com.wbao.dianniu.customView.LoadingWaitDialog;
import com.wbao.dianniu.customView.NoDoubleClickListener;
import com.wbao.dianniu.data.KnowHisData;
import com.wbao.dianniu.data.KnowPraseData;
import com.wbao.dianniu.data.KnowledgeData;
import com.wbao.dianniu.db.KnowDbHelper;
import com.wbao.dianniu.emojiUtils.EmotionMainFragment;
import com.wbao.dianniu.listener.IKnowledgeAddListener;
import com.wbao.dianniu.listener.IKnowledgeDetailListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.KnowAddManger;
import com.wbao.dianniu.manager.KnowDetailManager;
import com.wbao.dianniu.update.KnowledgeHelper;
import com.wbao.dianniu.utils.ActivityUtils;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.PermissionUtils;
import com.wbao.dianniu.utils.Utils;
import com.wbao.dianniu.xrichtext.RichTextEditor;
import com.wbao.dianniu.xrichtext.SDCardUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 写干货
 * <p>
 * Created by Administrator on 2017/8/31.
 */

public class CreateKnowActivity extends AppCompatActivity implements IKnowledgeAddListener, View.OnClickListener,
        IKnowledgeDetailListener {

    /**
     * 标题左侧的返回皱键
     */
    private ImageButton backBtn;
    /**
     * 标题
     */
    private TextView titleTV;
    /**
     * 发布
     */
    private Button rightBtn;
    private static final int PHOTO_SUCCESS = 1;
    private RichTextEditor richTextEditor;
    private ImageView addPic;
    private EditText mTitle;
    private ImageView aFriendIV;
    private KnowAddManger manager;
    private Map<Integer, String> noticeJson = new HashMap<Integer, String>();
    private static final int REQ_CODE = 8888;
    private Dialog pDialog;

    private ImageView emojiBtn;
    //    private RelativeLayout mInfoRL;
    private EmotionMainFragment emotionMainFragment;

    private KnowDetailManager knowDetailManager;
    private int knowledgeId;
    public static final String mBitmapStart = "{\"image\":\"";
    public static final String mBitmapMH = "\"";
    public static final String mBitmapSplit = ",";
    public static final String mBitmapWidth = "\"imgWidth\":";
    public static final String mBitmapHeight = "\"imgHeight\":";
    public static final String mBitmapEnd = "}";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityUtils.setStatusBarColor(this);
        setContentView(R.layout.activity_create_knowledge);
        initView();
        initManager();
        initData();
        initListener();
        mTitle.post(new Runnable() {
            @Override
            public void run() {
                mTitle.requestFocus();
            }
        });

    }

    private void initListener() {
        // 图片删除事件
        richTextEditor.setOnRtImageDeleteListener(new RichTextEditor.OnRtImageDeleteListener() {

            @Override
            public void onRtImageDelete(String imagePath) {
                boolean isOK = SDCardUtil.deleteFile(imagePath);
                if (isOK) {
//                    showToast("删除成功："+imagePath);
                }
            }
        });
        // 图片点击事件
        richTextEditor.setOnRtImageClickListener(new RichTextEditor.OnRtImageClickListener() {
            @Override
            public void onRtImageClick(String imagePath) {


            }
        });

    }

    private void initView() {
        backBtn = findViewById(R.id.back_button);
        backBtn.setOnClickListener(this);
        titleTV = findViewById(R.id.title);
        titleTV.setText(getResources().getString(R.string.write_knowledge));
        rightBtn = findViewById(R.id.right_button);
        rightBtn.setVisibility(View.VISIBLE);
        rightBtn.setText(getResources().getString(R.string.release));

        richTextEditor = findViewById(R.id.create_know_richtext);
        mTitle = findViewById(R.id.create_knowledge_title);
        aFriendIV = findViewById(R.id.know_add_friends);
        aFriendIV.setOnClickListener(this);
        addPic = findViewById(R.id.know_chose_pic);
        addPic.setOnClickListener(this);
        rightBtn.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (check()) {
                    // 组织数据
                    String content = getRichTextContent();
                    String noticeJ = Utils.toHeavyNoticeJson(noticeJson, content);
                    Integer id = null;
                    if (0 != knowledgeId) {
                        id = knowledgeId;
                    }
                    manager.knowledgeAdd(GlobalContext.getAccountId(), id, mTitle.getText().toString(), content, noticeJ);
                }
            }
        });

        emojiBtn = findViewById(R.id.emoji);

        mTitle.addTextChangedListener(watcher);

    }

    @NonNull
    private String getRichTextContent() {
        List<RichTextEditor.EditData> editList = richTextEditor.buildEditData();
        StringBuffer content = new StringBuffer();
        for (RichTextEditor.EditData itemData : editList) {
            if (itemData.inputStr != null) {
                content.append(itemData.inputStr);
            } else if (itemData.imagePath != null) {
                String tempUrl = mBitmapStart + itemData.uploadName + mBitmapMH + mBitmapSplit + mBitmapWidth + itemData.bitmapWidht + mBitmapSplit + mBitmapHeight + itemData.bitmapHeight + mBitmapEnd;
//                content.append("<img src=\"").append(itemData.imagePath).append("\"/>");
                content.append(tempUrl);
            }
        }
        return content.toString();

    }


    TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() == 30) {
                Notification.toast(CreateKnowActivity.this, "标题最多允许输入30个字符");
            }
        }
    };

    private void initData() {
        Intent intent = getIntent();
        knowledgeId = intent.getIntExtra(Const.INTENT_KNOWLEDGE_ID, 0);
        if (0 != knowledgeId) {     // 编辑界面跳转过来的 请求详情数据
            knowDetailManager = new KnowDetailManager(this);
            knowDetailManager.addKnowledgeDetailListener(this);
            knowDetailManager.knowledgeDetail(GlobalContext.getAccountId(), knowledgeId);
        } else {
            initHisData();
        }

    }

    private void initHisData() {
        // 取消保存的草稿箱状态
        KnowDbHelper dbHelper = new KnowDbHelper(CreateKnowActivity.this);
        if (dbHelper.getStatus(GlobalContext.getAccountId())) {
            KnowHisData knowHisData = dbHelper.query(GlobalContext.getAccountId());
            knowledgeId = knowHisData.getKnowledgeId();
            KnowledgeData knowledgeData = new KnowledgeData();
            knowledgeData.setId(knowHisData.getKnowledgeId());
            knowledgeData.setSubject(knowHisData.getSubject() == null ? "" : knowHisData.getSubject());
            knowledgeData.setContent(knowHisData.getContent() == null ? "" : knowHisData.getContent());
            knowledgeData.setNoticeJson(knowHisData.getNoticeJson() == null ? "" : knowHisData.getNoticeJson());
            display(knowledgeData);
        }
    }

    private void display(KnowledgeData data) {
        if (null == data)
            return;
        mTitle.setText(data.getSubject() == null ? "" : data.getSubject());
        List<KnowPraseData> hisList = splitImageContentByImages(data.getContent(), data.getNoticeJson());
        richTextEditor.initHistoryData(hisList);
    }

    class FindClass {
        public int index;
        public String content;
    }

    private void initManager() {
        manager = new KnowAddManger(this);
        manager.addKnowledgeAddListener(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PHOTO_SUCCESS:
                    Uri uri = data.getData();
                    if (!TextUtils.isEmpty(uri.getAuthority())) {
                        //查询选择图片
                        Cursor cursor = getContentResolver().query(uri, new String[]{MediaStore.Images.Media.DATA},
                                null, null, null);
                        //返回 没找到选择图片
                        if (null == cursor) {
                            return;
                        }
                        //光标移动至开头 获取图片路径
                        cursor.moveToFirst();
                        // 图片路径
                        String pathImage = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                        cursor.close();
                        // 将图片传到服务器，获取到Url地址
                        String uploadName = "image_" + StringUtils.getUUID();
                        // 将图片上传到服务器
                        pDialog = LoadingWaitDialog.createLoadingDialog(this, "上传中...");
                        pDialog.setCancelable(true);
                        pDialog.show();
                        //图片选择成功，上传图片到cdn，得到cdn的路径
                        HeadPresenter presenter = new HeadPresenter(CreateKnowActivity.this);
                        presenter.addUploadListener(new MyUploadListener(pathImage, uploadName));
                        presenter.uploadImageNotCompress(pathImage, uploadName);
                    }
                    break;
                case PermissionUtils.TAKE_PHOTO:
                    File file = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
                    //图片选择成功，上传图片到cdn，得到cdn的路径
                    String uploadName = "image_" + StringUtils.getUUID();
                    pDialog = LoadingWaitDialog.createLoadingDialog(this, "上传中...");
                    pDialog.setCancelable(true);
                    pDialog.show();
                    //图片选择成功，上传图片到cdn，得到cdn的路径
                    HeadPresenter presenter = new HeadPresenter(CreateKnowActivity.this);
                    presenter.addUploadListener(new MyUploadListener(file.getPath(), uploadName));
                    presenter.uploadImageUrl(file.getPath(), uploadName);
                    break;
                case REQ_CODE:
                    String userName = data.getStringExtra(Const.INTENT_NICENAME);
                    int friendId = data.getIntExtra(Const.BUNDLE_ACCOUNTID, 0);
                    if (userName != null && 0 != friendId) {
                        noticeJson.put(friendId, userName);// 加入noticeJson
                        SpannableString spannableString = new SpannableString("@" + userName);
                        Editable editable = richTextEditor.getFocusEditText().getEditableText();
                        int index = richTextEditor.getFocusEditText().getSelectionStart();
                        editable.insert(index, spannableString);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        if (null != manager) {
            manager.removeKnowledgeAddListener(this);
        }
        if (null != knowDetailManager) {
            knowDetailManager.removeKnowledgeDetailListener(this);
        }


    }


    class MyUploadListener implements UploadListener {
        private String filePath;
        private String uploadName;

        public MyUploadListener(String filePath, String uploadName) {
            this.filePath = filePath;
            this.uploadName = uploadName;
        }

        @Override
        public void onUploading(UploadTask uploadTask) {

        }

        @Override
        public void onUploadFailed(UploadTask uploadTask, FailReason failReason) {
            // TODO Auto-generated method stub
            if (null != pDialog && pDialog.isShowing()) {
                pDialog.dismiss();
            }
            Notification.toast(CreateKnowActivity.this, "上传失败");
        }

        @Override
        public void onUploadComplete(UploadTask uploadTask) {
            if (null != pDialog && pDialog.isShowing()) {
                pDialog.dismiss();
            }
            // 如果activity被销毁
            richTextEditor.insertImage(filePath, richTextEditor.getMeasuredWidth(), uploadName);

        }

        @Override
        public void onUploadCancelled(UploadTask uploadTask) {
            if (null != pDialog && pDialog.isShowing()) {
                pDialog.dismiss();
            }
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_button:
                // 保存草稿内容
                String content = getRichTextContent();
                if (TextUtils.isEmpty(mTitle.getText().toString()) && TextUtils.isEmpty(content)) {
                    finish();
                } else {
                    CustomDialog.Builder builder = new CustomDialog.Builder(this);
                    builder.setTitle("保存到草稿箱吗？");
                    builder.setPositiveButton(getResources().getString(R.string.confirm),
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    // 保存到草稿箱操作...
                                    save();
                                    finish();
                                }
                            });
                    builder.setNegativeButton(getResources().getString(R.string.cancel),
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    // 取消保存的草稿箱状态
                                    KnowDbHelper dbHelper = new KnowDbHelper(CreateKnowActivity.this);
                                    dbHelper.updataStatus(GlobalContext.getAccountId(), 0);
                                    // 新数据 直接取消草稿箱状态 再从新得到状态值
                                    finish();
                                }
                            });
                    builder.create().show();
                }
                break;
            case R.id.know_add_friends:
                Intent intent = new Intent();
                intent.setClass(CreateKnowActivity.this, SelectFriendActivity.class);
                startActivityForResult(intent, REQ_CODE);
                break;
            case R.id.know_chose_pic:
                //选择图片
                final CharSequence[] items = {"手机相册", "相机拍摄"};
                AlertDialog dlg = new AlertDialog.Builder(CreateKnowActivity.this).setTitle("选择图片").setItems(items,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int item) {
                                //这里item是根据选择的方式,
                                //在items数组里面定义了两种方式, 拍照的下标为1所以就调用拍照方法
                                if (item == 1) {
                                    //拍照
                                    PermissionUtils.getInstance().intentToCamera(CreateKnowActivity.this);
                                } else {
                                    PermissionUtils.getInstance().intentToPhoto(CreateKnowActivity.this, PHOTO_SUCCESS, 1, null);
                                }
                            }
                        }).create();
                dlg.show();
                break;
            default:
                break;
        }
    }

    private boolean check() {
        if (TextUtils.isEmpty(mTitle.getText().toString().trim())) {
            Notification.toast(this, "标题不能为空");
            return false;
        }

        String content = getRichTextContent();
        if (TextUtils.isEmpty(content.trim())) {
            Notification.toast(this, "内容不能为空");
            return false;
        }
        return true;
    }

    /**
     * 保存数据到数据库
     */
    private void save() {
        KnowDbHelper dbHelper = new KnowDbHelper(this);
        KnowHisData data = new KnowHisData();
        if (0 != knowledgeId) {
            data.setKnowledgeId(knowledgeId);
        }
        data.setAccoundId(GlobalContext.getAccountId());
        data.setSubject(mTitle.getText().toString());
        String content = getRichTextContent();
        data.setContent(content);
        // 去重noticeJson
        String noticeJ = Utils.toHeavyNoticeJson(noticeJson, content);
        data.setNoticeJson(noticeJ);
        dbHelper.saveKnowData(data);
        // 保存草稿箱状态true
        dbHelper.updataStatus(GlobalContext.getAccountId(), 1);

    }

    @Override
    public void onKnowledgeAddFailure(int errorCode, String errorMsg) {
        Notification.toast(this, errorMsg == null ? "" : errorMsg);
    }

    @Override
    public void onKnowledgeAddSuccess(KnowledgeData obj) {
        Notification.toast(this, "发布成功，等待审核");
        // 取消保存的草稿箱状态
        KnowDbHelper dbHelper = new KnowDbHelper(CreateKnowActivity.this);
        dbHelper.updataStatus(GlobalContext.getAccountId(), 0);

        // 如果是修改活动成功 把修改的数据通知到我发布的界面
        if (0 != knowledgeId) {
            KnowledgeHelper.getInstance().modifyOneData(knowledgeId, obj);
        } else {
            // 通知到界面
            KnowledgeHelper.getInstance().addNotify(obj);
        }
        //  发布成功
        this.finish();
    }

    @Override
    public void onKnowledgeDetailFailure(int errorCode, String errorMsg) {

    }

    @Override
    public void onKnowledgeDetailSuccess(KnowledgeData data) {
        if (null != data) {
            display(data);
        }

    }

    private List<KnowPraseData> splitImageContentByImages(String content, String noticeJson) {
        List<KnowPraseData> mContentList = new ArrayList<>();
        Pattern p = Pattern.compile("\\{\"image\":[^}]*\\}");
        Matcher m = p.matcher(content);
        List<FindClass> resultList = new ArrayList<>();
        while (m.find()) {
            String tmp = m.group();
            FindClass find = new FindClass();
            find.index = content.indexOf(tmp);
            find.content = tmp;
            resultList.add(find);
        }

        int preIndex = 0;
        for (int i = 0; i < resultList.size(); i++) {
            FindClass find = resultList.get(i);
            String str = "";
            if (find.index > 0) {
                str = content.substring(preIndex, find.index);
                KnowPraseData praseData = new KnowPraseData();
                praseData.index = 0;
                praseData.type = 1;
                praseData.content = str;
                praseData.noticeJson = noticeJson;
                mContentList.add(praseData);
            }
            KnowPraseData data = new KnowPraseData();
            data.index = find.index;
            data.content = find.content;
            data.type = 2;
            data.noticeJson = null;
            mContentList.add(data);
            preIndex = find.index + find.content.length();
        }
        if (preIndex < content.length()) {
            KnowPraseData data = new KnowPraseData();
            data.type = 1;
            data.index = preIndex;
            data.content = content.substring(preIndex, content.length());
            data.noticeJson = noticeJson;
            mContentList.add(data);
        }
        return mContentList;
    }


}
